/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hss01248.dialog.comp;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Image;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class GifLoad {
    private static int delay = 100;
    private static int count = 3;
    private List<PixelMap> pixelMapList = new ArrayList<>();
    private Image img;
    private AnimatorValue animatorValue;
    private int index;
    private AnimatorValue.ValueUpdateListener updateListener
            = new AnimatorValue.ValueUpdateListener() {
        @Override
        public void onUpdate(AnimatorValue animator, float v) {
            img.setPixelMap(pixelMapList.get((int) (v * pixelMapList.size())));
            img.invalidate();
        }
    };

    /**
     * gif load init
     * @param inputStream file input stream
     */
    public void init(InputStream inputStream)
    {
        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
        decodingOpts.allowPartialImage = true;
        sourceOptions.formatHint = "image/gif";
        ImageSource imageSource = ImageSource.create(inputStream, sourceOptions);

        if (imageSource != null) {
            index = 0;
            while (imageSource.createPixelmap(index, decodingOpts) != null) {
                pixelMapList.add(imageSource.createPixelmap(index, decodingOpts));
                index++;
            }
        }
    }

    /**
     * load gif
     * @param image image
     */
    public void loadGif(Image image) {
        img = image;
        animatorValue = new AnimatorValue();
        animatorValue.setCurveType(Animator.CurveType.LINEAR);
        animatorValue.setDelay(delay);
        animatorValue.setLoopedCount(Animator.INFINITE);//无限次循环
        animatorValue.setDuration(index / count * delay);
        animatorValue.setValueUpdateListener(updateListener);
        animatorValue.start();
    }
}
